#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QSqlQuery>
#include <QSqlError>


void MainWindow::on_pushButtonTestSqlite_clicked()
{
    //加入数据库
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("MyData.db3");

    //打开数据库
    if (!db.open())
    {
        //读取错误信息
        qDebug() << "ERROR:" << db.lastError().text();
        return;
    }

    //创建数据表
    QSqlQuery query;
    query.exec("CREATE TABLE students ("
               "id INTEGER PRIMARY KEY AUTOINCREMENT, "
               "name VARCHAR NOT NULL, "
               "score INTEGER NOT NULL, "
               "photo BLOB NOT NULL)");

    //增加一条记录
    query.prepare("INSERT INTO students (name, score, photo) "
                  "VALUES (:name, :score, :photo)");

    query.bindValue(":name", "wangwu");
    query.bindValue(":score", 99);
    query.bindValue(":photo", QByteArray("BinData", 8));
    query.exec();

    //删除一条记录
    query.exec("DELETE FROM students WHERE id = 1");

    //修改指定记录
    query.prepare("UPDATE students SET photo = :photo WHERE name = 'wangwu'");
    query.bindValue(":photo", QByteArray("NewBinData", 11));
    query.exec();

    //查找相关记录
    query.exec("SELECT * FROM students WHERE name = 'wangwu'");
    while (query.next())
    {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        QByteArray photo = query.value(3).toByteArray();
    }

    //关闭数据库
    db.close();
}
